package com.pe.pgn.clubpgn.webapp.controller.catalogo;

import java.util.Calendar;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.support.SessionStatus;

import com.pe.pgn.clubpgn.common.CLPConstantes;
import com.pe.pgn.clubpgn.domain.ClpbCategoria;
import com.pe.pgn.clubpgn.domain.ClpdArticulo;
import com.pe.pgn.clubpgn.domain.ClpdTipoTarjetaPersona;
import com.pe.pgn.clubpgn.domain.ClpmCatalogo;
import com.pe.pgn.clubpgn.domain.beans.BNArticulo;
import com.pe.pgn.clubpgn.domain.beans.BNCatalogoDetalle;
import com.pe.pgn.clubpgn.domain.beans.BNVariablesSistema;
import com.pe.pgn.clubpgn.service.ArticuloService;
import com.pe.pgn.clubpgn.service.CatalogoService;
import com.pe.pgn.clubpgn.service.CategoriaService;
import com.pe.pgn.clubpgn.service.NoExisteAlmacenException;
import com.pe.pgn.clubpgn.service.NoExisteArticuloException;
import com.pe.pgn.clubpgn.service.TarjetaPersonaService;
import com.pe.pgn.clubpgn.service.VariableGlobalService;
import com.pe.pgn.clubpgn.webapp.controller.BaseFormController;
import com.pe.pgn.clubpgn.webapp.util.CalendarUtil;

/**
 * @author Edwin Farfan
 */
@Controller
@RequestMapping("/catalogo/**")
public class CatalogoController  extends BaseFormController{

	@Autowired
	private CatalogoService service;

	@Autowired
	private CategoriaService categoriaService;
	
	@Autowired
	private VariableGlobalService variableGlobalService;
	
	@Autowired
	private ArticuloService articuloService;
	
	@Autowired
	private TarjetaPersonaService tarjetaPersonaService;
	
	@RequestMapping(value = "/catalogolist.html")
    public void listarCatalogos(Model model) {

		List<ClpmCatalogo> catalogos= service.obtenerListaCatalogos();
		model.addAttribute("catalogos", catalogos);
		List<ClpdTipoTarjetaPersona> tiposTarjetasPersonas = tarjetaPersonaService.obtenerTiposTarjetasPersonas();
		model.addAttribute("tiposTarjetasPersonas", tiposTarjetasPersonas);
		
		model.addAttribute("date_format", CLPConstantes.DATE_PATTERN);
    }
	
	@RequestMapping(value = "/catalogoform.html", method = RequestMethod.GET)
	public @ModelAttribute("catalogo") ClpmCatalogo verCatalogo(
				@RequestParam(value = "id", required = false) Long id, Model model) {
		
		BNVariablesSistema variables=variableGlobalService.obtenerVariables();
	
		model.addAttribute("date_format", CLPConstantes.DATE_PATTERN);
		model.addAttribute("fechaActual",CalendarUtil.calendarToString(CLPConstantes.DATE_PATTERN, Calendar.getInstance()));
		
		List<ClpdTipoTarjetaPersona> tiposTarjetasPersonas = tarjetaPersonaService.obtenerTiposTarjetasPersonas();
		model.addAttribute("tiposTarjetasPersonas", tiposTarjetasPersonas);
		String maximo="";
		
		if (id != null) {
			
			ClpmCatalogo catalogo = service.obtenerCatalogo(id);
			
			
			catalogo.setInicioVigencia(CalendarUtil.calendarToString(CLPConstantes.DATE_PATTERN, catalogo.getDaInicioVigencia()));
			catalogo.setFinCanje(CalendarUtil.calendarToString(CLPConstantes.DATE_PATTERN,catalogo.getDaFinCanje()));
			
			boolean vigente = service.vigenciaCatalogo(catalogo);
			
			model.addAttribute("catalogoVigente",vigente);
			
			if(catalogo.getDaFinCanje().before(Calendar.getInstance())){
				
				model.addAttribute("inactivarCatalogo","true" );
			}
							
			if(vigente){
				
				ClpdTipoTarjetaPersona tipoTarjetaPersona = service.obtenerTipoTarjetaPersona(catalogo.getClpdTipoTarjetaPersona().getId());
				model.addAttribute("tipoTarjeta", tipoTarjetaPersona);
			}
			
			service.setEliminacionPremioCatalogo(catalogo);	
			
			model.addAttribute("variables", variables);
			
			
			maximo=service.devolvermaximoCodPremioInstantaneo(catalogo.getInicioVigencia(), catalogo.getFinCanje());
			
			model.addAttribute("maximo", maximo);
			return catalogo;
		}
		
		
		maximo=service.devolvermaximoCodPremioInstantaneo("sysdate","sysdate");
		model.addAttribute("maximo", maximo);
		model.addAttribute("variables", variables);
		
		return new ClpmCatalogo();
	}
	
	
	@RequestMapping(value = "/articuloForCatalogo.html", method = RequestMethod.GET)
	public String  listarArticulos(Model model) {
		
		List<ClpdArticulo> articulos = articuloService.obtenerArticulos();
		List<ClpbCategoria> categorias = categoriaService.obtenerCategorias();
		
		
		model.addAttribute("articulos", articulos);
		model.addAttribute("categorias", categorias);
	
		
		return "/wizard/articulocatalogowizardform";
	}
	
	@RequestMapping(value = "/premioCodInstantaneo.html", method = RequestMethod.GET)
	public String  listarPremios(
			@RequestParam(value="articuloCode", required=true)String idArticulo,Model model) {
		
		String idCatalogo="";
		List<BNCatalogoDetalle> premios = service.obtenerPremiosCatalogos(idCatalogo, idArticulo);
		List<ClpmCatalogo> catalogo	= service.obtenerCatalogos();
	
		
		model.addAttribute("idArticulo",idArticulo);
		model.addAttribute("premios", premios);
		model.addAttribute("catalogo", catalogo);
	
	
		return "/wizard/premiocatalogowizardform";
	}

	@RequestMapping(value = "/catalogoform.html", method = RequestMethod.POST)
	public String guardarCatalogo(@ModelAttribute("catalogo") ClpmCatalogo catalogo,
			BindingResult result, SessionStatus status, HttpServletRequest request, Model model) {
		
		String retorno = null;
		if(catalogo.getId() != null){
			retorno = "redirect:catalogoform.html?id="+catalogo.getId();
		}else{
			List<ClpdTipoTarjetaPersona> tiposTarjetasPersonas = tarjetaPersonaService.obtenerTiposTarjetasPersonas();
			model.addAttribute("tiposTarjetasPersonas", tiposTarjetasPersonas);
			model.addAttribute("method", "Add");
			retorno = "/catalogo/catalogoform";
		}
		
		try {	
			int ecatalogo=0;
			int parcatalogo=service.sonCatalogosParalelos(catalogo.getInicioVigencia(), catalogo.getFinCanje());
			
			if(parcatalogo==0){

			ecatalogo= service.existeCatalogoRangoFecha(catalogo.getInicioVigencia(),
			catalogo.getFinCanje(),catalogo.getId());
			
			if(ecatalogo > 0){
			
				String[] arrayStr = new String[2];
				arrayStr[0] = catalogo.getInicioVigencia();
				arrayStr[1] = catalogo.getFinCanje();
			
				saveError(request, getText("catalogoform.existe",arrayStr, request.getLocale()));
				return retorno;
				}
			}
			catalogo.setCoCodigoCatalogo(catalogo.getCoCodigoCatalogo().trim());
			catalogo.setDeCatalogo(catalogo.getDeCatalogo().trim());
			
			ecatalogo = service.existeCatalogoDescription(
			catalogo.getDeCatalogo(),catalogo.getId());			
			if(ecatalogo > 0){
				saveError(request, getText("catalogoform.existe.description",request.getLocale()));
				return retorno;
			}
			
			ecatalogo = service.existeCatalogoCodigoCatalog(
			catalogo.getCoCodigoCatalogo(),catalogo.getId());			
			if(ecatalogo > 0){
				saveError(request, getText("catalogoform.existe.code",request.getLocale()));
				return retorno;
			}
		
			int varGuardar = service.saveCatalogo(catalogo);			
			if(varGuardar == 1){
				//se guardo correctamente
				saveMessage(request, getText("catalogoform.added", catalogo.getDeCatalogo().length() > CLPConstantes.LIMITE_CADENA ?
						catalogo.getDeCatalogo().substring(0, CLPConstantes.LIMITE_CADENA)
						.concat(CLPConstantes.PUNTOS_SUSPENSIVOS) : catalogo.getDeCatalogo(), 
						request.getLocale()));
			}else{
				saveError(request, getText("catalogoForm.codigo.instantaneo.repetido", request.getLocale()));
				return "/catalogo/catalogoform";
				
			}
			return "redirect:catalogolist.html";
			
		} catch(NoExisteAlmacenException e){
			saveError(request, getText("catalogoform.no.exite.almacen.virtual", request.getLocale()));
			return retorno;
		}catch(NoExisteArticuloException e){
			saveError(request, getText("catalogoform.no.existe.articulo", request.getLocale()));
			return retorno;
		}catch (Exception e) {
			saveError(request, getText("errors.general", request.getLocale()));
			return retorno;
		}
	}	
	
	@RequestMapping(value = "/eliminarcatalogo.html")
	public String eliminarCatalogo(@RequestParam(value = "id", required = true) Long id, 
			HttpServletRequest request) {

		try {
			int varEliminado=service.eliminarCatalogo(id); 
				
			if(varEliminado==1) {
				saveError(request, getText("catalogoform.no.deleted.dependencias", request.getLocale()));
				return "redirect:catalogoform.html?id="+id+"&from=list";
			}else if (varEliminado==2){
				saveError(request, getText("catalogoform.no.deleted.fecha.vigencia", request.getLocale()));
				return "redirect:catalogoform.html?id="+id+"&from=list";
			}else{
				saveMessage(request, getText("catalogoform.deleted", request.getLocale()));
				return "redirect:catalogolist.html";
			}
		} 
		catch (Exception e) {
			saveError(request, getText("errors.general", request.getLocale()));
			return "redirect:catalogoform.html?id="+id+"&from=list";
		}
	}		

	@RequestMapping(value="inactivarCatalogo.html")
	public String inactivarCatalogo(@RequestParam(value = "id", required = true) Long id, 
			HttpServletRequest request) {
		try {
			ClpmCatalogo catalogo = service.obtenerCatalogo(id);
			service.inactivarCatalogo(catalogo);
			saveMessage(request, getText("catalogoform.inactivado", request.getLocale()));			
			
		} catch (Exception e) {
			saveError(request, getText("errors.general", request.getLocale()));
			return "/catalogo/catalogoform";
		}
		return "redirect:catalogolist.html";
	}
	

	@RequestMapping(value="darbajapremiocatalogo.html")
	public String darBajaPremioCatalogo(
			@RequestParam(value="id", required=true)Long id,
			@RequestParam(value="idCatalogo", required=true) Long idCatalogo,
			@RequestParam(value="idArticulo", required=true) Long idArticulo,
			HttpServletRequest request){
		
		
		if(id==null || idCatalogo==null || idArticulo==null){	
			saveError(request, getText("errors.general", request.getLocale()));
		}else{

		int encontro=0;
	
		BNArticulo articulo= new BNArticulo();
		articulo = articuloService.obtenerArticuloPorID(idArticulo);
		
		if(articulo.getStInstantaneoVale().equals(CLPConstantes.ST_VERDADERO) ){
			encontro=service.darbajaPremio(id);
			if(encontro!=0){
				saveMessage(request, getText("catalogoForm.darbaja.exito", request.getLocale()));		
			}else{
				saveError(request, getText("catalogoForm.darbaja.error", request.getLocale()));
			}
			
		}else{
			BNCatalogoDetalle catalogo=service.obtenerCatalogoxPremio(idCatalogo,id);
			service.desasignarPremios(catalogo);
			encontro=service.darbajaPremio(id);
	
			if(encontro!=0){
				saveMessage(request, getText("catalogoForm.darbaja.exito", request.getLocale()));		
			}else{
				saveError(request, getText("catalogoForm.darbaja.error", request.getLocale()));
			}
		}
		
		}
		return "redirect:catalogoform.html?id="+idCatalogo+"&from=list";
		
	}
}

